package com.globisoft.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.globisoft.dao.GoodReceivedNoteDao;
import com.globisoft.domain.GRN;
import com.globisoft.util.ComboBoxObject;

@Repository("GoodReceivedNoteDao")
public class GoodReceivedNoteDaoImpl implements GoodReceivedNoteDao {

	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public boolean saveGRN(GRN grn) {

		sessionFactory.getCurrentSession().save(grn);
		return false;
	}

	@Override
	public List<ComboBoxObject> getAllGRNType() {
		List<ComboBoxObject> list = new ArrayList<ComboBoxObject>();
		Session session = sessionFactory.getCurrentSession();
		String query = "SELECT * FROM grn_types";
		List<Object[]> result = session.createSQLQuery(query).list();
		for(Object[] obj: result) {
			list.add(new ComboBoxObject((int)obj[0], (String)obj[1]));
			
		}
		return list;
	}

	@Override
	public List<ComboBoxObject> getAllPurchaseOrder() {
		
		List<ComboBoxObject> list = new ArrayList<ComboBoxObject>();
		Session session = sessionFactory.getCurrentSession();
		String query = "SELECT * FROM purchase_orders";
		List<Object[]> result = session.createSQLQuery(query).list();
		for(Object[] obj: result) {
			list.add(new ComboBoxObject((int)obj[0], (String)obj[1]));
			
		}
		return list;
	}

	@Override
	public List<ComboBoxObject> getSuppliersByPurchaseOrder(int purchaseOrderId) {
		
		List<ComboBoxObject> list = new ArrayList<ComboBoxObject>();
		Session session = sessionFactory.getCurrentSession();
		String query = "SELECT BP_SID, BP_CODE FROM business_partners " +
				"INNER JOIN purchase_orders ON business_partners.BP_SID = purchase_orders.partner_sid " +
				"and purchase_orders.purchase_order_sid = "+purchaseOrderId;
		
		List<Object[]> result = session.createSQLQuery(query).list();
		for(Object[] obj: result) {
			list.add(new ComboBoxObject((int)obj[0], (String)obj[1]));
			
		}
		return list;
	}

}
